package com.project.personalfundmanager.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.ui.RootPanel;
import com.project.personalfundmanager.client.common.GlobalRegister;
import com.project.personalfundmanager.client.facebook.Callback;
import com.project.personalfundmanager.client.facebook.FBCore;
import com.project.personalfundmanager.client.facebook.FBEvent;
import com.project.personalfundmanager.client.facebook.FrontpageViewController;

public class PersonalFundManager implements EntryPoint
{
	FBCore fbCore = GWT.create( FBCore.class );
	FBEvent fbEvent = GWT.create( FBEvent.class );
	FrontpageViewController loginLink = new FrontpageViewController();

	String APPID = "b0410d760f2f19705fa213805e231d0d";
	private boolean status = true;
	private boolean xfbml = true;
	private boolean cookie = true;

	private boolean isProdMode = GWT.isProdMode();

	@Override
	public void onModuleLoad()
	{
		GlobalRegister.setFbCore( fbCore );
		initFacebook();
	}

	public void initFacebook()
	{
		fbCore.init( APPID, status, cookie, xfbml );
		addSessionChangeListener();
		addLoginListener();
		renderHomeView();
	}

	private void renderHomeView()
	{
		if ( isProdMode && fbCore.getSession() == null )
		{
			RootPanel.get().clear();
			RootPanel.get().add( loginLink );
		}
		else
		{
			RootPanel.get().remove( loginLink );
			new Application().load();
		}
	}

	private void addSessionChangeListener()
	{
		fbEvent.subscribe( "auth.sessionChange", new Callback<JavaScriptObject>()
		{
			public void onSuccess( JavaScriptObject result )
			{
				renderHomeView();
			}
		} );
	}

	private void addLoginListener()
	{
		class LoginStatusCallback extends Callback<JavaScriptObject>
		{
			public void onSuccess( JavaScriptObject response )
			{
				renderHomeView();
			}
		}

		LoginStatusCallback loginStatusCallback = new LoginStatusCallback();
		fbCore.getLoginStatus( loginStatusCallback );
	}
}
